(function ( $ ) {
    $.fn.customerScreen = function(options ) {
     return this.each(function() {
          alert($(this).attr( "data-toggle" ))
        });

    };
}( jQuery ));

      var customerTransactionGrid,customerListGrid;

      $(function(){

        function initCustomerGrid(){
         customerListGrid=  $("#customerGrid").jqGrid({
                        url: "search",
                        datatype: "json",
                        mtype: "GET",
                        colNames: ["Name", "Nick Name", "City","Phone Number","Mobile", "Company", 'Actions'],
                        colModel: [
                            { name: "nickName", width: 125 },
                            { name: "name", width: 160 },
                            { name: "address.city", width: 80, align: "left" },
                            { name: "phoneNumber", width: 80, align: "left" },
                            { name: "mobileNumber", width: 80, align: "left" },
                            { name: "companyName", width: 150, align: "left" },
                            { name : 'customerId', index:'customerId', sortable:false,editable:false ,formatter:actionFormat, unformat:actionUnFormat,key:true,formatoptions: {icon: 'fa-pencil',icon2: 'fa-list', link_class: 'add-link-class',model:'#customerForm',model2:'#customerTransaction'}},
                        ],
                        pager: "#customerGridPager",
                         postData: {
                                query: function() { return $("#search-name").val(); },
                                customerType: function() { return $("#search-customerType").val(); }

                            } ,
                        toolbarfilter: true,
                        rowNum: 10,
                        rowList: [10, 20, 30],
                        sortname: "customerId",
                        sortorder: "desc",
                        viewrecords: true,
                        gridview: true,
                        autoencode: true,
                        caption: "Customers" ,
                        height:400,
                        autowidth : true,
                        jsonReader : {root:"customers"},
                        gridComplete: function(){
                            var ids = jQuery("#customerGrid").jqGrid('getDataIDs');
                        }

                        });
             initGridUI();
        }

    function initCustomerTrxGrid(){
        customerTransactionGrid=  $("#customerTransactionGrid").jqGrid({
              url: "transactionHistory",
              datatype: "local",
              mtype: "GET",
              colNames: ["Type", "Num", "Date","Amount"],
              colModel: [
                  { name: "transactionType" ,align: "left" },
                  { name: "transactionId" ,align: "left"},
                  { name: "transactionDate", align: "left" },
                  { name: "transactionAmount", align: "left",formatter:'currency' ,formatoptions:currencyformatoptions},

              ],
              pager: "#customerTransactionGridPager",
               postData: {
                      transactionType: function() { return $("#search-transaction-type").val(); },
                      dateRange: function() { return $("#search-transaction-dateRange").val(); },
                      customerId: function() { return $("#trx-customerId").val(); }

                  } ,
               toolbarfilter: true,
              rowNum: 10,
              rowList: [10, 20, 30],
              sortname: "transactionDate",
              sortorder: "desc",
              viewrecords: true,
              gridview: true,
              autoencode: true,
              caption: "Transactions" ,
              height:400,
              width : '800',
              footerrow : true,
              userDataOnFooter : true,
              toolbarfilter: true,
               jsonReader: {
                      root: 'transactions',
                     userdata: function (obj) {
                          return {
                              transactionAmount: obj.totalTransactionAmount
                          };
                      }
                  },
              gridComplete: function(){
                var ids = jQuery("#customerGrid").jqGrid('getDataIDs');

              }

              });
        initGridUI();
        }
    initCustomerGrid();
    initCustomerTrxGrid();




                $('#new-customer-form1').validator({custom:function($el){alert($el); return false;}}).on('submit', function (event) {
                       if (event.isDefaultPrevented()) {
                        // handle the invalid form...
                      } else {
                            event.preventDefault();

                            var options = {
                                url:       'save' ,
                                type:      'post' ,
                                dataType:  'json' ,
                                clearForm: true  ,
                                resetForm: true  ,
                                timeout:   9000  ,
                                success:    function() {
                                   customerListGrid.trigger("reloadGrid");
                                    $('#customerForm').modal('hide')
                                 }  ,
                                  error:    function() {
                                    $("#model-error-block").show();

                                 }
                            };

                            $("#new-customer-form").ajaxSubmit(options) ;
                            return false;
                      }
                });

             function actionFormat( cellvalue, options, rowObject ){
                    return "<button class='btn btn-xs btn-default btn-quick' title='Edit Customer' data-toggle='modal' data-target='"+options.colModel.formatoptions.model+"' data-value='"+cellvalue+"' ><i class='fa "+options.colModel.formatoptions.icon+"'></i></button>"+
                    "<button class='btn btn-xs btn-default btn-quick' title='View Transaction' data-toggle='modal'  data-target='"+options.colModel.formatoptions.model2+"' data-value='"+cellvalue+"' ><i class='fa "+options.colModel.formatoptions.icon2+"'></i></button>";

               }
              function actionUnFormat1( cellvalue, options, cell){
                     	return $('img', cell).attr('src');
                }

                initAccountSearch(selectAccount);

       $( "#customerDetailButton").button().click(function () {
             $( "#customerinfo" ).show();
             $( "#customerDetail" ).addClass("hide");
        });

        function enableCustomerSearch(){
             $( "#customerinfo" ).show();
             $( "#customerDetail" ).addClass("hide");
        }


        $('button.modelWindow').on('shown.bs.modal', function () {
                 e.preventDefault();
                 var title = $(this).data('title');
                 $("#customer-payment-model-title").html(title);
        });



           $('#new-payment-form1').validator().on('submit', function (event) {
                      if (event.isDefaultPrevented()) {
                        // handle the invalid form...
                      } else {
                            event.preventDefault();

                            var options = {
                                url:       'savePayment' ,
                                type:      'post' ,
                                dataType:  'json' ,
                                clearForm: true  ,
                                resetForm: true  ,
                                timeout:   9000  ,
                                success:    function() {
                                   customerListGrid.trigger("reloadGrid");
                                    $('#customerForm').modal('hide')
                                 }  ,
                                  error:    function() {
                                   alert('Error');
                                 }
                            };

                            $("#new-payment-form").ajaxSubmit(options) ;
                            return false;
                      }
                });




    });

   function selectAccount( event, ui ) {
        var customerInfo = ui.item.customer;
        $( "#customerId" ).val(customerInfo.customerId);
        $( "#customer-company" ).html(customerInfo.companyName);
         $( "#customer-name" ).html(customerInfo.name);
         $( "#customer-city" ).html(customerInfo.address.city);
         $( "#customer-mobile" ).html(customerInfo.mobileNumber);
         $( "#customerinfo" ).hide();
          $( "#customerDetail" ).removeClass("hide");
         $(this).val("");
         return true;
       }

  function showTransactionDetails(index,modelObj){

            $.ajax({url: "getDetails",
                dataType: "json",
                data: {
                        "customerId": index
                      },success: function(customerObj){
                            myApp.hidePleaseWait();
                            if(customerObj.customerId)
                               {
                                       loadFormData(customerObj,'customerTransaction');
                                         modelObj.find('.modal-title').text('' + customerObj.name)
                                        $("#trx-customerId").val(index);

                                      //   modelObj.find("#trx-customerId").value(index)

                                        customerTransactionGrid.jqGrid('setGridParam',{datatype: 'json'});
                                        customerTransactionGrid.trigger("reloadGrid");

                                }
                              else{

                                  }
                     }
               });


          }
  function showCustomerDetails(index,modelObj){
         $.ajax({url: "getDetails", dataType: "json",data: {
                                          "customerId": index
                      },success: function(productObj){
                      if(productObj.customerId)
                       {
                          modelObj.find('.modal-title').text('' + productObj.name)
                          loadFormData(productObj,'customerForm');
                       }
                        else{

                      }
                }});
    }




